package com.tepth.maintenancesystem.view;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.ProgressStyle;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.SysApplication;
import com.tepth.maintenancesystem.api.HttpClient;
import com.tepth.maintenancesystem.api.MaintainHttp;
import com.tepth.maintenancesystem.api.OutLogin;
import com.tepth.maintenancesystem.bean.User;
import com.tepth.maintenancesystem.bean.VehicleMaintain;
import com.tepth.maintenancesystem.datepicker.MonthDateView;
import com.tepth.maintenancesystem.presenter.MaintainAdapter;
import com.tepth.maintenancesystem.untils.DateUtils;
import com.tepth.maintenancesystem.untils.ToastUtils;
import com.tepth.maintenancesystem.untils.Untils;
import com.tepth.maintenancesystem.view.fragment.SearchStaticListSupportFragment;
import com.xdandroid.materialprogressview.MaterialProgressView;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.carbs.android.library.MDDialog;
import xyz.sahildave.widget.SearchViewLayout;

public class MaintainListActivity extends AppCompatActivity implements PopupWindow.OnDismissListener, OutLogin {

    private static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.main_maintain_bar_text)
    TextView maintainBarText;

    @BindView(R.id.visible_bar_number_done)
    TextView visible_bar_number_done;

    @BindView(R.id.visible_bar_number_doing)
    TextView visible_bar_number_doing;

    @BindView(R.id.visible_bar_number_ready)
    TextView visible_bar_number_ready;

    @BindView(R.id.main_date_bar_layout)
    LinearLayout dateBarLayout;

    @BindView(R.id.main_date_bar_text)
    TextView dateBarText;

    @BindView(R.id.main_date_bar_arrow)
    ImageView dateBarArrow;

    @BindView(R.id.vehicle_list)
    SuperRecyclerView vehicle_list;

    @BindView(R.id.maintain_loading_layout)
    LinearLayout maintain_loading_layout;

    @BindView(R.id.progress_view)
    MaterialProgressView progressView;

    @BindView(R.id.nodata_notification)
    LinearLayout nodata_notification;

    private ImageView barDate_left, barDate_right;
    private TextView barDate_tv, barDate_today;
    private MonthDateView monthDateView;

    private int screenWidth, screenHeight;//屏幕宽高
    private Context context;
    private PopupWindow popupWindow;//pop层
    private List<VehicleMaintain> datas;//保养总集合
    private List<VehicleMaintain> ready_datas = new ArrayList<>();//待处理集合
    private List<VehicleMaintain> doing_datas = new ArrayList<>();//作业中集合
    private List<VehicleMaintain> done_datas = new ArrayList<>();//已完成集合
    private MaintainAdapter mtAdapter;//保养列表适配器
    private String dateString;//当前查看的日期
    private int index = 0;//0为全部，1为未处理，2为作业中，3为已完成
    private LoadingDialog loadingDialog;
    private String result_beginMaintain;//保养请求结果，是否开始保养
    private VehicleMaintain click_item;
    private HashMap<Integer, List<Integer>> notFinishWorkMap = new HashMap<>();
    private String searchNumber = "";//搜索的车辆编号

    private SearchViewLayout searchViewLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintain_list);
        SysApplication.getInstance().addActivity(this);
        context = this;
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        initScreenWidth();
        initView();
        getMaintainList(1);


        searchViewLayout = (SearchViewLayout) findViewById(R.id.search_view_container);
        searchViewLayout.setExpandedContentSupportFragment(this, new SearchStaticListSupportFragment());
        searchViewLayout.handleToolbarAnimation(toolbar);
        searchViewLayout.setCollapsedHint("请输入车辆编号");
        searchViewLayout.setExpandedHint("请输入车辆编号");


        ColorDrawable collapsed = new ColorDrawable(ContextCompat.getColor(context, R.color.colorPrimary));
        ColorDrawable expanded = new ColorDrawable(ContextCompat.getColor(context, R.color.default_color_expanded));
        searchViewLayout.setTransitionDrawables(collapsed, expanded);
        searchViewLayout.setSearchListener(new SearchViewLayout.SearchListener() {
            @Override
            public void onFinished(String searchKeyword) {
                searchViewLayout.collapse();
                if (datas.size() == 0)
                    return;
                VehicleMaintain temp = null;
                for (int i = 0; i < datas.size(); i++) {
                    if (datas.get(i).getVehicleNumber().equals(searchKeyword)) {
                        temp = datas.get(i);
                    }
                }
                if (temp != null) {
                    click_item = temp;
                    searchNumber = searchKeyword;
                    if (click_item.getWorkStatusCode().equals("ReadyWork")) {
                        showBeginDialog(click_item);
                    } else if (click_item.getWorkStatusCode().equals("FinishWork") || click_item.getWorkStatusCode().equals("CompletedWork") || click_item.getWorkStatusCode().equals("FinishPlan")) {
                        if (click_item.getWorkStatusCode().equals("FinishPlan")) {
                            ToastUtils.showToast(context, "报修信息还未录入,无法开始保养");
                        }
                        Intent intent = new Intent();
                        intent.setClass(MaintainListActivity.this, MaintainCompletedDetailsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("Maintain", click_item);
                        intent.putExtra("MaintainBundle", bundle);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(MaintainListActivity.this, MaintainDetailsActivitiy.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("Maintain", click_item);
                        bundle.putString("dateString", dateString);
                        intent.putExtra("MaintainBundle", bundle);
                        startActivityForResult(intent, 1001);
                    }
                } else {
                    Snackbar.make(searchViewLayout, "未搜索到车辆", Snackbar.LENGTH_LONG).show();
                }
//
            }
        });
        searchViewLayout.setOnToggleAnimationListener(new SearchViewLayout.OnToggleAnimationListener() {
            @Override
            public void onStart(boolean expanding) {
//                if (expanding) {
//                    fab.hide();
//                } else {
//                    fab.show();
//                }
            }

            @Override
            public void onFinish(boolean expanded) {
                if (expanded) {
                    if (searchNumber != "") {
                        EditText editText = (EditText) searchViewLayout.findViewById(R.id.search_expanded_edit_text);
                        editText.setText(searchNumber);
                        editText.setSelection(searchNumber.length());//将光标移至文字末尾
                    }
                } else {
                    if (searchNumber != "") {
                        ((TextView) searchViewLayout.findViewById(R.id.search_box_collapsed_hint)).setText(searchNumber);
                    }
                }
            }
        });
        searchViewLayout.setSearchBoxListener(new SearchViewLayout.SearchBoxListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                Log.d(TAG, "beforeTextChanged: " + s + "," + start + "," + count + "," + after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Log.d(TAG, "onTextChanged: " + s + "," + start + "," + before + "," + count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d(TAG, "afterTextChanged: " + s);
            }
        });
    }

    @OnClick({R.id.main_date_bar_layout, R.id.img_home_setting, R.id.img_home_barcode, R.id.main_maintain_bar_layout_all, R.id.main_maintain_bar_layout_ready, R.id.main_maintain_bar_layout_doing, R.id.main_maintain_bar_layout_done})
    public void click(View view) {
        if (searchViewLayout.isExpanded())
            return;
        switch (view.getId()) {
            case R.id.main_maintain_bar_layout_all:
                index = 0;
                initAdapter();
//                if (popupWindow != null)
//                    popupWindow.dismiss();
                break;
            case R.id.main_maintain_bar_layout_ready:
                index = 1;
                initAdapter();
//                if (popupWindow != null)
//                    popupWindow.dismiss();
                break;
            case R.id.main_maintain_bar_layout_doing:
                index = 2;
                initAdapter();
//                if (popupWindow != null)
//                    popupWindow.dismiss();
                break;
            case R.id.main_maintain_bar_layout_done:
                index = 3;
                initAdapter();
//                if (popupWindow != null)
//                    popupWindow.dismiss();
                break;
//            case R.id.main_maintain_bar_layout:
//                try {
//                    showPopupWindow(view, 1);
//                    maintainBarArrow.setImageResource(R.drawable.arrow_up);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                break;
            case R.id.main_date_bar_layout:
                try {
                    showPopupWindow(view, 3);
                    dateBarArrow.setImageResource(R.drawable.arrow_up);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.img_home_setting:
                Intent intent = new Intent();
                intent.setClass(this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.img_home_barcode:
//                Intent intent2=new Intent();
//                intent2.setClass(this,CaptureActivity.class);
//                startActivity(intent2);
                ToastUtils.showToast(context, "该功能暂未开放");
                break;
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        User user = Untils.getUserList(context).get(Untils.getUserIndex(context));//取出用户
        maintainBarText.setText(user.getPersonName());

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        vehicle_list.setLayoutManager(layoutManager);
        vehicle_list.setRefreshEnabled(true);//可以定制是否开启下拉刷新
        vehicle_list.setLoadMoreEnabled(true);//可以定制是否开启加载更多
        vehicle_list.setLoadingListener(new PullToRefreshListener());//下拉刷新，上拉加载的监听
        vehicle_list.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);//下拉刷新的样式
        vehicle_list.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);//上拉加载的样式
        vehicle_list.setArrowImageView(R.drawable.arrow_down);//设置下拉箭头
        dateString = this.getIntent().getStringExtra("dateString");
        if (dateString == null || dateString == "")
            dateString = DateUtils.getNowCalendar(0);
        dateBarText.setText(dateString);//设置日期

        progressView.setColorSchemeColors(new int[]{Untils.getColor(context, R.color.home_background)});
        progressView.setProgressBackgroundColor(Untils.getColor(context, R.color.white));
    }

    private View dateContentView = null;//日期视图
    private int popupWindowFlag = 0;

    /**
     * 显示PopupWindow
     *
     * @param anchor
     * @param flag
     */
    public void showPopupWindow(View anchor, int flag) {
        popupWindow = new PopupWindow(this);
        popupWindow.setOnDismissListener(this);
        popupWindowFlag = flag;
        View contentView = null;
        switch (flag) {
//            case 1:
//                contentView = LayoutInflater.from(context).inflate(
//                        R.layout.main_bar_popupwindow_status, null);
//                //显示数字
//                TextView ready_bar_number = (TextView) contentView.findViewById(R.id.ready_bar_number);
//                TextView doing_bar_number = (TextView) contentView.findViewById(R.id.doing_bar_number);
//                TextView done_bar_number = (TextView) contentView.findViewById(R.id.done_bar_number);
//                ready_bar_number.setText(ready_datas.size() + "");
//                doing_bar_number.setText(doing_datas.size() + "");
//                done_bar_number.setText(done_datas.size() + "");
//                //绑定按钮事件
//                LinearLayout all_bar_linearlayout = (LinearLayout) contentView.findViewById(R.id.all_bar_linearlayout);
//                LinearLayout ready_bar_linearlayout = (LinearLayout) contentView.findViewById(R.id.ready_bar_linearlayout);
//                LinearLayout doing_bar_linearlayout = (LinearLayout) contentView.findViewById(R.id.doing_bar_linearlayout);
//                LinearLayout done_bar_linearlayout = (LinearLayout) contentView.findViewById(R.id.done_bar_linearlayout);
//                all_bar_linearlayout.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        index = 0;
//                        initAdapter();
//                        maintainBarText.setText("全部");
//                        visibleBarNumber.setVisibility(View.GONE);
//                        popupWindow.dismiss();
//                    }
//                });
//                ready_bar_linearlayout.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        index = 1;
//                        initAdapter();
//                        maintainBarText.setText("待处理");
//                        visibleBarNumber.setVisibility(View.VISIBLE);
//                        visibleBarNumber.setText(ready_datas.size() + "");
//                        visibleBarNumber.setBackgroundResource(R.drawable.design_ready_point);
//                        popupWindow.dismiss();
//                    }
//                });
//                doing_bar_linearlayout.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        index = 2;
//                        initAdapter();
//                        maintainBarText.setText("处理中");
//                        visibleBarNumber.setVisibility(View.VISIBLE);
//                        visibleBarNumber.setText(doing_datas.size() + "");
//                        visibleBarNumber.setBackgroundResource(R.drawable.design_doing_point);
//                        popupWindow.dismiss();
//                    }
//                });
//                done_bar_linearlayout.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        index = 3;
//                        initAdapter();
//                        maintainBarText.setText("已完成");
//                        visibleBarNumber.setVisibility(View.VISIBLE);
//                        visibleBarNumber.setText(done_datas.size() + "");
//                        visibleBarNumber.setBackgroundResource(R.drawable.design_done_point);
//                        popupWindow.dismiss();
//                    }
//                });
//                popupWindow.setWidth(screenWidth / 2);
//                popupWindow.setHeight(350);
//                break;
            case 2:
//                contentView = LayoutInflater.from(context).inflate(
//                        R.layout.main_bar_popupwindow_type, null);
//                popupWindow.setWidth(screenWidth / 3);
//                popupWindow.setHeight(350);
                break;
            case 3:
                if (dateContentView == null) {
                    contentView = LayoutInflater.from(context).inflate(
                            R.layout.main_bar_popupwindow_date, null);
                    dateContentView = contentView;
                    initBarDateView(contentView);
                } else {
                    contentView = dateContentView;
                }
                popupWindow.setWidth(screenWidth);
                int tempHeight = 0;
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
                    tempHeight = (int) (screenHeight * 0.6);
                } else {
                    tempHeight = screenHeight / 3;
                }
                popupWindow.setHeight(tempHeight);
                break;
        }
        popupWindow.setContentView(contentView);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.showAsDropDown(anchor);

    }

    /**
     * 初始化列表适配器
     */
    private void initAdapter() {
        List<VehicleMaintain> adapter_datas = new ArrayList<>();
        switch (index) {
            case 0:
                adapter_datas = datas;
                break;
            case 1:
                adapter_datas = ready_datas;
//                maintainBarText.setText("待处理");
//                visibleBarNumber.setVisibility(View.VISIBLE);
//                visibleBarNumber.setText(ready_datas.size() + "");
//                visibleBarNumber.setBackgroundResource(R.drawable.design_ready_point);
                break;
            case 2:
                adapter_datas = doing_datas;
//                maintainBarText.setText("处理中");
//                visibleBarNumber.setVisibility(View.VISIBLE);
//                visibleBarNumber.setText(doing_datas.size() + "");
//                visibleBarNumber.setBackgroundResource(R.drawable.design_doing_point);
                break;
            case 3:
                adapter_datas = done_datas;
//                maintainBarText.setText("已完成");
//                visibleBarNumber.setVisibility(View.VISIBLE);
//                visibleBarNumber.setText(done_datas.size() + "");
//                visibleBarNumber.setBackgroundResource(R.drawable.design_done_point);
                break;
        }
        mtAdapter = new MaintainAdapter(context, adapter_datas);
        vehicle_list.setAdapter(mtAdapter);
        mtAdapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {//点击开始保养
                if (searchViewLayout.isExpanded())
                    return;
                click_item = (VehicleMaintain) item;
                if (click_item.getWorkStatusCode().equals("ReadyWork")) {
                    showBeginDialog(click_item);
                } else if (click_item.getWorkStatusCode().equals("FinishWork") || click_item.getWorkStatusCode().equals("CompletedWork") || click_item.getWorkStatusCode().equals("FinishPlan")) {
                    if (click_item.getWorkStatusCode().equals("FinishPlan")) {
                        ToastUtils.showToast(context, "报修信息还未录入,无法开始保养");
                    }
                    Intent intent = new Intent();
                    intent.setClass(MaintainListActivity.this, MaintainCompletedDetailsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("Maintain", click_item);
                    intent.putExtra("MaintainBundle", bundle);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(MaintainListActivity.this, MaintainDetailsActivitiy.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("Maintain", click_item);
                    bundle.putString("dateString", dateString);
                    intent.putExtra("MaintainBundle", bundle);
                    startActivityForResult(intent, 1001);
                }
            }
        });
        vehicle_list.setNoLoadMore(true);
        if (adapter_datas != null) {
            if (adapter_datas.size() == 0) {
                vehicle_list.setVisibility(View.GONE);
                maintain_loading_layout.setVisibility(View.GONE);
                progressView.setVisibility(View.GONE);
                nodata_notification.setVisibility(View.VISIBLE);
                ToastUtils.showToast(context, "没有保养计划");
            } else {
                maintain_loading_layout.setVisibility(View.GONE);
                nodata_notification.setVisibility(View.GONE);
                vehicle_list.setVisibility(View.VISIBLE);
            }
        } else {
            vehicle_list.setVisibility(View.GONE);
            maintain_loading_layout.setVisibility(View.GONE);
            progressView.setVisibility(View.GONE);
            nodata_notification.setVisibility(View.VISIBLE);
            ToastUtils.showToast(context, "没有保养计划");
        }
    }

    /**
     * 显示开始保养Dialog
     *
     * @param obj
     */
    private void showBeginDialog(final VehicleMaintain obj) {
        String[] messageContent = new String[]{"是否开始保养作业"};
        new MDDialog.Builder(context)
//                .setContentView(R.layout.vehicle_dialog)
                .setMessages(messageContent)
                .setContentViewOperator(new MDDialog.ContentViewOperator() {
                    @Override
                    public void operate(View contentView) {
//                        EditText et = (EditText)contentView.findViewById(R.id.et_remark);
//                        et.setHint("请填写报修内容");
                    }
                }).setTitle("开始保养")
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("开始保养", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loadingDialog = new LoadingDialog(context);
                        loadingDialog.setInterceptBack(false)
                                .setLoadingText("正在开始...");
                        loadingDialog.show();
                        new Thread() {
                            @Override
                            public void run() {
                                result_beginMaintain = MaintainHttp.updateDriverAndRemark(context, obj.getId() + "");
                                myHandler.sendEmptyMessage(3);
                                super.run();
                            }
                        }.start();
                    }
                })
                .setWidthMaxDp(600)
                .setShowButtons(true)
                .create()
                .show();
    }

    /**
     * 初始化日历
     *
     * @param contentView
     */
    private void initBarDateView(View contentView) {
        List<Integer> list = new ArrayList<>();
        if (notFinishWorkMap.size() > 0) {
            try {
                int month = DateUtils.getDateMonthFormString(dateString);
                list = notFinishWorkMap.get(month);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        barDate_left = (ImageView) contentView.findViewById(R.id.bardate_left);
        barDate_right = (ImageView) contentView.findViewById(R.id.bardate_right);
        barDate_tv = (TextView) contentView.findViewById(R.id.date_text);
        barDate_today = (TextView) contentView.findViewById(R.id.tv_today);
        monthDateView = (MonthDateView) contentView.findViewById(R.id.monthDateView);
        monthDateView.setTextView(barDate_tv);
        monthDateView.setDaysHasThingList(list);
        monthDateView.setDateClick(new MonthDateView.DateClick() {

            @Override
            public void onClickOnDate() {
                if (monthDateView.getmSelDay() == 0)
                    return;
                dateString = monthDateView.getmSelYear() + "-" + DateUtils.addZeroForNum((monthDateView.getmSelMonth() + 1) + "", 2) + "-" + DateUtils.addZeroForNum(monthDateView.getmSelDay() + "", 2);
                dateBarText.setText(dateString);
                getMaintainList(1);
                popupWindow.dismiss();
            }
        });
        barDate_left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                monthDateView.onLeftClick();
                List<Integer> list = new ArrayList<>();
                if (notFinishWorkMap.size() > 0) {
                    list = notFinishWorkMap.get(monthDateView.getmSelMonth() + 1);
                }
                monthDateView.setDaysHasThingList(list);
            }
        });

        barDate_right.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                monthDateView.onRightClick();
                List<Integer> list = new ArrayList<>();
                if (notFinishWorkMap.size() > 0) {
                    list = notFinishWorkMap.get(monthDateView.getmSelMonth() + 1);
                }
                monthDateView.setDaysHasThingList(list);
            }
        });

        barDate_today.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                monthDateView.setTodayToView();
                List<Integer> list = new ArrayList<>();
                if (notFinishWorkMap.size() > 0) {
                    int month = DateUtils.getNowMonth();
                    list = notFinishWorkMap.get(month);
                }
                monthDateView.setDaysHasThingList(list);
            }
        });
    }

    /**
     * @return void 返回类型
     * @Title: initScreenWidth
     * @Description: 查看自身的宽高
     * @author lmw
     */
    private void initScreenWidth() {
        DisplayMetrics dm = new DisplayMetrics();
        dm = getResources().getDisplayMetrics();
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
    }

    /**
     * popupWindow关闭的执行方法
     */
    @Override
    public void onDismiss() {
//        maintainBarArrow.setImageResource(R.drawable.arrow_down);
        dateBarArrow.setImageResource(R.drawable.arrow_down);
        if (popupWindowFlag == 3) {
            dateString = monthDateView.getmSelYear() + "-" + DateUtils.addZeroForNum((monthDateView.getmSelMonth() + 1) + "", 2) + "-" + DateUtils.addZeroForNum(monthDateView.getmSelDay() + "", 2);
            dateBarText.setText(dateString);
            getMaintainList(1);
        }
    }

    /**
     * 退出登陆
     */
    @Override
    public void outLogin() {
        myHandler.sendEmptyMessage(0);
    }

    private class PullToRefreshListener implements SuperRecyclerView.LoadingListener {

        @Override
        public void onLoadMore() {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
//                    addData();
                    vehicle_list.completeLoadMore();
                }
            }, 3000);
        }

        @Override
        public void onRefresh() {
//            if(dataList.size() >= 50){
//                superRecyclerView.setNoMore(true);
//                return;
//            }
            getMaintainList(2);
        }
    }

    /**
     * 统计各种类型的保养，并显示在界面上
     */
    private void stateStatistics() {
        ready_datas.clear();
        doing_datas.clear();
        done_datas.clear();
        if (datas != null && !datas.isEmpty()) {
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getWorkStatusCode().equals("FinishWork") || datas.get(i).getWorkStatusCode().equals("CompletedWork")) {//完成
                    done_datas.add(datas.get(i));
                } else if (datas.get(i).getWorkStatusCode().equals("UnderWork")) {//作业中
                    doing_datas.add(datas.get(i));
                } else {
                    ready_datas.add(datas.get(i));
                }
            }
        }
        visible_bar_number_ready.setText(ready_datas.size() + "");
        visible_bar_number_doing.setText(doing_datas.size() + "");
        visible_bar_number_done.setText(done_datas.size() + "");
    }

    /**
     * 保养作业列表
     *
     * @param what
     */
    public void getMaintainList(final int what) {
        if (what == 1) {
            maintain_loading_layout.setVisibility(View.VISIBLE);
            vehicle_list.setVisibility(View.GONE);
        }
//        if (datas != null)
//            datas.clear();
        new Thread() {
            @Override
            public void run() {
                datas = MaintainHttp.getMtList(context, DateUtils.getSpecifiedDayAfter(dateString, 0), DateUtils.getSpecifiedDayAfter(dateString, 1), MaintainListActivity.this);
                myHandler.sendEmptyMessage(what);
                super.run();
            }
        }.start();
    }

    /**
     * 获取未完成作业日期集合
     */
    private void getNotFinishWork() {
        new Thread() {
            @Override
            public void run() {
                ArrayList<String> dateArrayList = MaintainHttp.getDicNotFinishWork(context);
                Message message = new Message();
                message.what = 4;
                Bundle bundle = new Bundle();
                bundle.putSerializable("dateList", dateArrayList);
                message.setData(bundle);
                myHandler.sendMessage(message);
                super.run();
            }
        }.start();
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://登陆超时
                    ToastUtils.showToast(context, "登录超时");
                    Intent intent2 = new Intent();
                    intent2.setClass(context, LoginActivity.class);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent2.putExtra("manual", "manual");
                    startActivity(intent2);
                    break;
                case 1://初始化列表
                    stateStatistics();
                    initAdapter();
                    maintain_loading_layout.setVisibility(View.GONE);
                    vehicle_list.setVisibility(View.VISIBLE);
                    getNotFinishWork();
                    break;
                case 2://上拉刷新列表
                    stateStatistics();
                    vehicle_list.completeRefresh();
//                    mtAdapter.notifyDataSetChanged();
//                    vehicle_list.setNoLoadMore(true);
                    initAdapter();
                    break;
                case 3://开始保养，并跳转保养作业界面
                    loadingDialog.close();
                    if (result_beginMaintain.equals(HttpClient.SUCCESS)) {
                        Intent intent = new Intent();
                        intent.setClass(MaintainListActivity.this, MaintainDetailsActivitiy.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("Maintain", click_item);
                        intent.putExtra("MaintainBundle", bundle);
                        startActivityForResult(intent, 1001);
                    } else if (result_beginMaintain.equals(HttpClient.ERROR_NET)) {
                        ToastUtils.showToast(context, "网络错误");
                    }
                    break;
                case 4:
                    ArrayList<String> dateList = (ArrayList<String>) msg.getData().getSerializable("dateList");
                    notFinishWorkMap = DateUtils.getDateFromMonthArrayList(dateList);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1001 && resultCode == MaintainHttp.RESULT_REFRESHLIST) {
            getMaintainList(1);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            String[] messageContent = new String[]{"是否退出"};
            new MDDialog.Builder(context)
                    .setMessages(messageContent)
                    .setTitle("提示")
                    .setNegativeButton(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    })
                    .setPositiveButton("退出", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SysApplication.getInstance().exit();
                        }
                    })
                    .setWidthMaxDp(600)
                    .setShowButtons(true)
                    .create()
                    .show();
        }
        return super.onKeyDown(keyCode, event);
    }
}
